package message

import (
	"encoding/json"
	"github.com/garyburd/redigo/redis"
	"log"
	"push"
	"rhelper"
	"time"
)

type Message struct {
	Type     string `json:"type"`
	Id       int    `json:"id"`
	To       string `json:"to"`
	From     string `json:"from"`
	FromName string `json:"fromName"`
	Title    string `json:"title"`
	Abstract string `json:"abstract"`
	Detail   string `json:"detail"`
	EventId  string `json:"eventId"`
	Stime    int    `json:"stime"`
}

type Notify struct {
	Uri string  `json:"uri"`
	Msg Message `json:"msg"`
}

func SendMessage(msg Message, cid string) error {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	log.Println("message: ", msg)
	to, err := redis.String(rconn.Do("HGET", rhelper.AccountHash+msg.To, "id"))
	if err != nil {
		log.Println("get user unique id failed:", err)
		return err
	}

	id, err := redis.Int(rconn.Do("INCR", rhelper.MsgIdHolder))
	if err != nil {
		log.Println("SendMessage err:", err)
		return err
	}

	msg.Id = id

	msg.Stime = int(time.Now().Unix())

	b, err := json.Marshal(msg)
	if err != nil {
		log.Println("SendMessage error:", err)
		return err
	}

	rconn.Send("MULTI")
	rconn.Send("HSET", rhelper.MsgHash+to, id, b)
	rconn.Send("RPUSH", rhelper.MsgURHash+to, id)
	_, err = rconn.Do("EXEC")
	if err != nil {
		log.Println("SendMessage err:", err)
		return err
	}

	// iphone message alert
	alert := msg.Abstract
	if msg.Type == "evtimer" {
		alert = msg.FromName + " timer task"
	} else if msg.Type == "state" {
		alert = msg.FromName + " state change"
	} else if msg.Type == "evtrigger" {
		alert = msg.FromName + " trigger"
	} else if msg.Type == "evsystem" && msg.Title == "offline" {
		alert = msg.FromName + " offline"
	}

	push.Send(msg.To, b, alert)
	return nil
}

func SendGmail(to string, msgBody string) {
	if to == "" {
		return
	}

	push.SendGmail(to, msgBody)
}
